//
//  HeaderWebViewController.m
//  ITHome
//
//  Created by lanou3g on 15/7/16.
//  Copyright (c) 2015年 YAX. All rights reserved.
//

#import "HeaderWebViewController.h"
#import "WebViewModel.h"
#import "CExpandHeader.h"
#import "NSDate+Extend.h"
#import "ReplyTableViewController.h"
#import "UMSocial.h"
#import "FMDBManage.h"
#import "LoginViewController.h"


@interface HeaderWebViewController ()<UIWebViewDelegate>

@property(nonatomic,strong)UIWebView *webView;
@property(nonatomic,strong)CExpandHeader *header;
@property(nonatomic,strong)UIImage *image;
@property (nonatomic, copy) NSString *shareTitle; // 分享和收藏的标题
@property (nonatomic, strong) UIImage *shareImage; // 分享的图片
@property (nonatomic, strong) NSString *created_at;// 收藏用的时间
@property(nonatomic,strong)UIButton *collectionBtn;// 收藏用的button;




@end

@implementation HeaderWebViewController
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    NSMutableArray *urlIDArray = [FMDBManage showAllUrlID];
    for (NSString *obj in urlIDArray)
    {
        if ([self.urlId isEqualToString:obj])
        {
            [self.collectionBtn setImage:[UIImage imageNamed:@"bt_list_more_collection_choice"] forState:UIControlStateNormal];
        }
    }
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [ProgressHUD progressHUDAnimation:self.view labelText:@"加载中"];
    self.webView = [[UIWebView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight - 64 - 49)];
    self.webView.delegate = self;
    _webView.scrollView.showsHorizontalScrollIndicator = NO;
    [self.view addSubview:self.webView];

    [self getRequest];
    // 设置导航栏
    [self loadNavigationIndfo];
    
    // 创建底部视图
    [self footerView];
    self.hidesBottomBarWhenPushed = YES;
    
}

#pragma - mark - 字体设置
- (void)webViewDidFinishLoad:(UIWebView *)webView
{

    CGFloat font = [[NSUserDefaults standardUserDefaults] floatForKey:@"fontSize"];

    if ((int)(font/14*100) == 0) {
        [webView stringByEvaluatingJavaScriptFromString:@"document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '100%'"];
        return;
    }
    NSString *string = [NSString stringWithFormat:@"document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '%d%%'",(int)(font/14*100)];
    [webView stringByEvaluatingJavaScriptFromString:string];

}

#pragma mark - 创建视图底部视图
- (void)footerView
{
    UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, kScreenHeight - 64 - 49, kScreenWidth, 49)];
    footerView.backgroundColor = [UIColor RGBColor:236 green:236 blue:236 alpha:1];
    
    // 线
    UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 0.3)];
    lineView.backgroundColor = [UIColor RGBColor:202 green:202 blue:202 alpha:1];
    [footerView addSubview:lineView];
    
    // 评论
    CGRect commentsFrame = CGRectMake(10, 5, kScreenWidth / 2, 39);
    UIButton *commentsBtn = [UIButton buttonWithFrame:commentsFrame image:@"search" highImage:@"search"];
    commentsBtn.backgroundColor = [UIColor randomColor];
    [commentsBtn addTarget:self action:@selector(commentsBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    
    CGRect commetsTextFrame = CGRectMake(10, 0, kScreenWidth / 2, 39);
    UILabel *commetsTextLabel = [[UILabel alloc] init];
    commetsTextLabel.frame = commetsTextFrame;
    commetsTextLabel.text = @"写评论...";
    commetsTextLabel.textColor = [UIColor grayColor];
    commetsTextLabel.font = [UIFont systemFontOfSize:14];
    [commentsBtn addSubview:commetsTextLabel];
    
    [footerView addSubview:commentsBtn];
    
    // 收藏
    CGRect conllectBtnFrame = CGRectMake(footerView.width / 1.8, 5, 37, 37);
    self.collectionBtn = [UIButton buttonWithFrame:conllectBtnFrame image:@"bt_list_more_collection_normal" highImage:@"bt_list_more_collection_choice"];
    [_collectionBtn addTarget:self action:@selector(collectionBtnAction) forControlEvents:UIControlEventTouchUpInside];
    [footerView addSubview:_collectionBtn];
    
    // 分享
    CGRect shareBtnFrame = CGRectMake(_collectionBtn.width + _collectionBtn.x + 10, 5, 37, 37);
    UIButton *shareBtn = [UIButton buttonWithFrame:shareBtnFrame image:@"bt_list_more_share_normal" highImage:@"bt_list_more_share_press"];
    [shareBtn addTarget:self action:@selector(shareBtnAction) forControlEvents:UIControlEventTouchUpInside];
    [footerView addSubview:shareBtn];
    
    // 刷新
    CGRect downloadBtnFrame = CGRectMake(shareBtn.width + shareBtn.x + 10, 5, 37, 37);
    UIButton *downloadBtn = [UIButton buttonWithFrame:downloadBtnFrame image:@"refresh" highImage:@"refresh-1"];
    [downloadBtn addTarget:self action:@selector(downloadBtnAction) forControlEvents:UIControlEventTouchUpInside];
    [footerView addSubview:downloadBtn];
    
    [self.view addSubview:footerView];
}

#pragma mark - 评论按钮触发事件
- (void)commentsBtnAction:(UIButton *)button
{
    
    // 评论
    [self commentsAction];
}

#pragma mark - 收藏按钮触发事情
- (void)collectionBtnAction
{
    // 判断登陆状态
    // 先取出登陆状态
    NSString *loginStatus = [[NSUserDefaults standardUserDefaults] stringForKey:kLoginStatus];
    if ([loginStatus isEqualToString:@"YES"])
    {
        // 收藏
        NSMutableArray *urlIDArray = [FMDBManage showAllUrlID];
        if (urlIDArray.count != 0)
        {
            for (NSString *obj in urlIDArray)
            {
                if ([self.urlId isEqualToString:obj])
                {
                    [FMDBManage deleteOneInfoWithUrlId:self.urlId];
                    [self.collectionBtn setImage:[UIImage imageNamed:@"bt_list_more_collection_normal"] forState:UIControlStateNormal];
                }
                else
                {
                    [FMDBManage insertOneInfo:self.urlId shareTitle:self.shareTitle created_at:self.created_at urlString:self.urlString commentsCount:self.commentsCount shareImageUrl:self.feature_img];
                    [self.collectionBtn setImage:[UIImage imageNamed:@"bt_list_more_collection_choice"] forState:UIControlStateNormal];
                }
            }
        }
        else
        {
            [FMDBManage creatTable];
            [FMDBManage insertOneInfo:self.urlId shareTitle:self.shareTitle created_at:self.created_at urlString:self.urlString commentsCount:self.commentsCount shareImageUrl:self.feature_img];
            [self.collectionBtn setImage:[UIImage imageNamed:@"bt_list_more_collection_choice"] forState:UIControlStateNormal];
        }

    }
    else // 跳转到登录
    {
        // 跳转到登陆页面
        LoginViewController *loginViewVc = [[LoginViewController alloc] init];
        //            [self.navigationController pushViewController:loginStatus animated:YES];
        UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:loginViewVc];
        nav.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
        [self presentViewController:nav animated:YES completion:nil];
    }

}

#pragma mark - 分享按钮触发事件
- (void)shareBtnAction
{
   // 分享
    [UMSocialSnsService presentSnsIconSheetView:self appKey:@"55a8c25567e58e15d8000cb2" shareText:[NSString stringWithFormat:@"%@ | 【IT家园】猛戳查看详情%@",self.shareTitle,self.url] shareImage:self.shareImage shareToSnsNames:[NSArray arrayWithObjects:UMShareToWechatSession,UMShareToQQ,UMShareToSina,UMShareToTencent ,UMShareToWechatTimeline,UMShareToQzone,UMShareToRenren,UMShareToEmail,UMShareToLWTimeline,UMShareToYXSession,nil] delegate:nil];
    
}

#pragma mark - 下载按钮触发事件
- (void)downloadBtnAction
{
    // 点击刷新回到顶部
    [self.webView.scrollView setContentOffset:CGPointMake(0, - 0) animated:YES];
}

#pragma mark - 设置导航栏
- (void)loadNavigationIndfo
{
    self.navigationController.navigationBar.translucent = NO;
    
    // 设置导航栏颜色
    self.navigationController.navigationBar.barTintColor = [UIColor RGBColor:71 green:128 blue:208 alpha:1];
    
    // 返回
    UIBarButtonItem *leftBackButton = [UIBarButtonItem itemWithTarget:self Action:@selector(backAction) image:@"home_back" highImage:@"home_back_highlighted"];
    self.navigationItem.leftBarButtonItem = leftBackButton;
    
    // 评论
    UIBarButtonItem *rightSaveButton  = [UIBarButtonItem itemWithTarget:self Action:@selector(commentsAction) image:@"contenttoolbar_hd_comment_light" highImage:@"contenttoolbar_hd_comment" title:self.commentsCount];
    self.navigationItem.rightBarButtonItem = rightSaveButton;
    
    // 标题
    [[UINavigationBar appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor whiteColor]}];
}

#pragma mark - 返回按钮触发事件
- (void)backAction
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - 评论
- (void)commentsAction
{

    ReplyTableViewController *reply = [[ReplyTableViewController alloc]init];
    reply.urlString = [NSString stringWithFormat:@"http://rong.36kr.com/api/v1/news/comments/%@?uid=155576",self.urlId];
    // 模态过去
    reply.commentsCount = self.commentsCount; //评论数
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:reply];
    nav.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
    [self presentViewController:nav animated:YES completion:nil];
}

- (void)getRequest
{
    [LORequestManger GET:self.urlString success:^(id response) {
        NSDictionary *dict = (NSDictionary *)response;
        NSDictionary *data = dict[@"data"];
        WebViewModel *model = [WebViewModel modelWithDict:data];
        NSDictionary *user = data[@"user"];
        model.name = [user objectForKey:@"name"];
        self.shareTitle = model.title;// 分享和收藏的标题
        self.created_at = [NSDate dateWithStringFromat:model.created_at];
        UIImageView *myImageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight * 0.25)];
        [myImageView sd_setImageWithURL:[NSURL URLWithString:model.feature_img]];
        self.shareImage = myImageView.image;
        _header = [CExpandHeader expandWithScrollView:_webView.scrollView expandView:myImageView];
        [self showNews:model];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//        YAXLog(@"%@",error);
        [ProgressHUD progressHUD:self.view labelText:@"加载失败"];
    }];
}

- (void)showNews:(WebViewModel *)model
{
    int width = kScreenWidth/1.05;
    int height = kScreenIp6(300);
    NSString * imgWidth = [NSString stringWithFormat:@"<img width=\"%d\" ",width];
    NSString *iframe = [NSString stringWithFormat:@"<iframe height=\"%d\" width=\"%d\" ",height,width];
    
    // 从bundle里获取css文件
    NSString *cssurl = [[NSBundle mainBundle]URLForResource:@"News" withExtension:@"css"].absoluteString;
    
    model.body_html = [model.body_html stringByReplacingOccurrencesOfString:@"<img " withString:imgWidth];
    model.body_html = [model.body_html stringByReplacingOccurrencesOfString:@"<iframe " withString:iframe];
    
    if ([model.body_html containsString:model.feature_img]) {
        NSRange range = [model.body_html rangeOfString:model.feature_img];
        NSString *string = [model.body_html substringFromIndex:range.length + range.location +6];
        NSString *titleString = [NSString stringWithFormat:@"<div class=\"title\">%@</div> <p class=\"time\">%@&nbsp&nbsp发表于&nbsp&nbsp%@</p> %@",model.title,model.name,[NSDate dateWithStringFromat:model.created_at],string];
        titleString =   [NSString stringWithFormat:@"%@<link rel=\"stylesheet\" href=\"%@\">",titleString,cssurl ];
        [_webView loadHTMLString:titleString baseURL:nil];
        return;
    }
    else
    {
        NSString *titleString = [NSString stringWithFormat:@"<div class=\"title\">%@</div> <div class=\"time\">%@&nbsp&nbsp发表于&nbsp&nbsp%@</div> %@",model.title,model.name,[NSDate dateWithStringFromat:model.created_at],model.body_html];
        titleString = [NSString stringWithFormat:@"%@<link rel=\"stylesheet\" href=\"%@\">",titleString,cssurl];
        [_webView loadHTMLString:titleString baseURL:nil];
    }
}

#pragma mark - 内容警告提示
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    [[SDImageCache sharedImageCache] clearMemory];
}


@end
